<?php

namespace api\modules\v1\controllers;

use addons\TfFutures\common\models\Bankinfo;
use addons\TfFutures\common\models\Logs;
use addons\TfFutures\common\models\Member;
use addons\TfFutures\common\models\Order;
use addons\TfFutures\common\models\Order as OrderModel;
use addons\TfFutures\services\OrderService;
use common\helpers\ResultDataHelper;
use common\models\common\Capital;
use common\models\common\PayLog;
use Yii;
use api\controllers\OnAuthController;
use common\models\forms\PayForm;

/**
 * 公用支付生成
 *
 * Class PayController
 * @package api\modules\v1\controllers
 * @author jianyan74 <751393839@qq.com>
 */
class PayTopController extends OnAuthController
{
    /**
     * @var PayForm
     */
    public $modelClass = '';
    protected $optional = ['notify','charge'];
    /**
     * 充值
     */
    public function actionCharge(){
        $fee = Yii::$app->request->post('money');
        if (empty($fee)){
            return ResultDataHelper::api(422, '充值金额不能为空');
        }
        if (!is_numeric($fee)){
            return ResultDataHelper::api(422, '充值金额格式不正确');
        }
        $member = Bankinfo::findOne(['member_id' => Yii::$app->user->identity->member_id,'status' => '2']);
        if(empty($member)) {
            return ResultDataHelper::api(422, '请先实名认证！！');
        }
        $fee = abs($fee);
        //支付成功后的跳转地址
        $doman = Yii::$app->request->post('from')=="mobile"?"http://app.leigetech.cn/#/index":"http://c.leigetech.cn/#/index?value=lation";
        //收集支付参数
        $tjurl = "https://s.starfireotc.com/payLink/mobile.html";
        $appkey = "e5adf08738ab4445bd73b7b6f6389c28";
        $md5Key = "8979c01784357786cbd351eb330867ec";
        $orderSn = "RJ".time().rand(1000,9999);
        $customerAmount  = '';
        $customerAmountCny  = $fee;//充值金额（人民币）
        $outOrderId   = $orderSn;//客户订单号
        $pickupUrl = $doman;//交易完成后的跳转地址
        $receiveUrl = 'http://'.$_SERVER['SERVER_NAME']."/api/v1/pay-top/notify";//通知回调地址
        $signType = 'MD5';//签名方式，固定MD5
        //生成sign
        $sign = md5($outOrderId.$customerAmount.$pickupUrl.$receiveUrl.$customerAmountCny.$signType.$md5Key);
        //跳转地址
        $tjurl = $tjurl."?outOrderId=".$orderSn."&customerAmount=&customerAmountCny=".$customerAmountCny."&APPKey=".$appkey."&pickupUrl=".$pickupUrl."&receiveUrl=".$receiveUrl."&signType=MD5&sign=".$sign;
        //记录日志
        $pay_log = new PayLog();
        $pay_log->out_trade_no  = $outOrderId;
        $pay_log->pay_fee       = $fee;
        $pay_log->member_id     = Yii::$app->user->identity->member_id;
        $pay_log->order_group   = "in";
        $pay_log->pay_time      = time();
        if ($pay_log->save()) {
            //返回url
            return ResultDataHelper::api(200, '请支付',$tjurl);
        }else{
            return ResultDataHelper::api(500, '日志记录错误');
        }
    }

    //支付回调
    public function actionNotify(){
        $customerAmount     = Yii::$app->request->post("customerAmount");//美元
        $customerAmountCny  = Yii::$app->request->post("customerAmountCny");//人民币
        $outOrderId         = Yii::$app->request->post("outOrderId");//
        $orderId            = Yii::$app->request->post("orderId");
        $signType           = Yii::$app->request->post("signType");
        $status             = Yii::$app->request->post("status");
        $sign               = Yii::$app->request->post("sign");
        $md5Key             = "8979c01784357786cbd351eb330867ec";
        $signstr            = md5($customerAmount.$customerAmountCny.$outOrderId.$orderId.$signType.$status.$md5Key);
        $data = [
            '充值美元：'.$customerAmount,
            '充值人民币：'.$customerAmount,
            '客户订单号：'.$customerAmount,
            '平台订单号：'.$customerAmount,
            'MD5：'.$customerAmount,
            '状态：'.$status,
            '签名：'.$sign,
            '生成签名:'.$signstr,
        ];
        $aString = '$data = '.var_export($data, true).';';
        //将数组存到指定的text文件中
        file_put_contents(__DIR__.'/pay.php', $aString);
        //验签
        if($signstr == $sign && $status == "success"){
            //获取用户充值记录
            $pay_log = PayLog::find()->where(['out_trade_no'=>$outOrderId])->one();
            if(empty($pay_log)){
                exit("error");
            }
            $pay_log->status = "1";
            //给用户充值
            $member = Member::findOne(['member_id'=>$pay_log->member_id]);
            if (empty($member)){
                exit("error");
            }
            $oldprice = $member->price;
            $member->price = bcadd($member->price,$customerAmount,4);
            $member->save();
            //记录用户资金日志
            $los = new Logs();
            $los::addLogs($pay_log->member_id,'资金转入',$customerAmount,$oldprice,$member->price,'用户充值，金额为'.$customerAmount);
            $pay_log->save();
            exit("success");
        } else {
            exit("error");
        }

    }

    /**
     * 用户提现
     * @return mixed
     */
    public function actionWithdrawal()
    {
        if (!Yii::$app->request->isPost) {
            return ResultDataHelper::api(403, 'Access done');
        }
        $member_id = Yii::$app->user->identity->member_id;
        $price = Yii::$app->request->post('price');
        if(!is_numeric($price)) {
            return ResultDataHelper::api(422, '请输入正确的提现金额');
        }

        $member_type = Bankinfo::find()->where(['member_id' => $member_id,'status' => '2'])->one();
//        print_r($member_type);exit;
        if(empty($member_type)) {
            return ResultDataHelper::api(422, '请先实名认证！！');
        }
        //获取用户可用资产
        $order = OrderModel::find()
            ->where([
                'member_id' => $member_id,
                'state' => '平仓',
                'status' => 1,
            ])->andWhere(['>=','open_time',time().' 00:00:00'])->select('sum(service_fee) as service_fee, sum(overfee) as overfee, sum(deposit) as deposit, sum(profit) as profit')
            ->one();
        //用户当天入金总额
        $money_in_day = PayLog::find()
            ->where(['member_id' => $member_id,'status' => 1,'order_group' => 'in'])
            ->andWhere(['>=','updated_at',strtotime(date("Y-m-d"),time())])
            ->select('sum(pay_fee) as pay_fee')
            ->asArray()
            ->one();
        $order_din = 'CJ'.time().rand(1000,9999);
        $member = Member::findOne(['member_id'=>$member_id]);
        if(bcsub($member->price,$money_in_day->pay_fee == null ? 0.00 : $money_in_day,4) < 0) {
            return ResultDataHelper::api(422, '可取资产不足');
        }
        $member->price = bcsub(bcsub($member->price,$money_in_day->pay_fee,4),$price,4);
        $member->price_blocked += $price;
        if($member->price < 0) {
            return ResultDataHelper::api(422, '提现金额不可大于可用资产');
        }
        $member->save();
        $with = Capital::addLogs($member_id,$order_din,$price,'out');
        if($with == FALSE){
            return ResultDataHelper::api(422, '提现失败');
        }
        return ResultDataHelper::api(200, '申请已提交');

    }


    //增加用户余额
    private static function addMoney($id,$money){
        $member = Member::findOne(['member_id'=>$id]);
        if (empty($member)){
            exit("error");
        }
        $member->price = bcadd($member->price,$money,4);
        $member->save();
    }
}